package com.jctrip.hotel.common.util;

import com.jctrip.hotel.common.context.BeanContext;

import java.util.*;

/**
 * 随机功能工具类
 */
public class RandomUtil {

    private static final String SEED_NUM = "0123456789";
    private static final String SEED_STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    public static String createRandomStr(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(SEED_STR.length());
            sb.append(SEED_STR.charAt(index));
        }
        return sb.toString();
    }

    public static String createRandomNum(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(SEED_NUM.length());
            sb.append(SEED_NUM.charAt(index));
        }
        return sb.toString();
    }

    public static String createOrderId() {
        return "330" + new Date().getTime() / 1000 + createRandomNum(3);
    }

    public static String createBookId() {
        return "51" + new Date().getTime() / 1000 + createRandomNum(3);
    }

    public static String getRandomItem(String key, String joinedStr, String delimiter) {
        RedisUtil redisUtil = BeanContext.getApplicationContext().getBean(RedisUtil.class);
        // 缓存中key的value还存在 直接拿第一个
        if(redisUtil.lGetListSize(key) > 0){
            return (String) (redisUtil.rightPop(key));
        }
        String[] items = joinedStr.split(delimiter);
        // 就一个 不存缓存 直接返回
        if (items.length == 0) {
            return joinedStr;
        }
        // 打乱下单key
        List<String> itemList = Arrays.asList(items);
        Collections.shuffle(itemList);
        // 加入缓存
        redisUtil.leftPushAll(key, new ArrayList<>(itemList));
        // 拿key中的第一个值
        return (String) (redisUtil.rightPop(key));
    }
}
